package com.wx_shop.api.util.wx.util;

import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wx_shop.api.comm.Constants;
import com.wx_shop.api.util.FastJsonConvert;
import com.wx_shop.api.util.HttpClientUtil;
import com.wx_shop.api.util.wx.dto.WeixinAccessTokenDomain;
import com.wx_shop.api.util.wx.dto.WeixinPayDomain;
import com.wx_shop.api.util.wx.dto.WeixinPayRes;
import com.wx_shop.api.util.wx.dto.WeixinUser;


public class WeixinApiUtil {
	static Logger logger = LoggerFactory.getLogger(WeixinApiUtil.class);
	private static DataExpiresIn<String> tokenData = new DataExpiresIn<String>();
	private static DataExpiresIn<String> ticketData = new DataExpiresIn<String>();
	
	/**
	 * 微信token get userinfo
	 * @param token
	 * @param openid
	 * @return
	 */
	public static WeixinUser getUserInfoByToken(String token, String openid) {
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid=" + openid + "&lang=zh_CN";
		
		logger.debug("url={}", url);
		String res = HttpClientUtil.httpGetRequest(url);
		
		if(StringUtils.isEmpty(res)) {
			logger.error("res=null");
			return null;
		}
		
		WeixinUser weixinUser = FastJsonConvert.convertJSONToObject(res, WeixinUser.class);
		logger.debug("weixinUser={}", weixinUser);
		
		return weixinUser;
	}
	
	/**
	 * 微信通过code获取token
	 * @param code
	 * @return
	 */
	public static WeixinAccessTokenDomain getUserTokenAndOpenidByCode(String code) {
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.WX_APPID + "&secret=" + Constants.WX_APPSECRET + "&code="+code+"&grant_type=authorization_code";
		
		logger.debug("url={}", url);
		String res = HttpClientUtil.httpGetRequest(url);
		
		if(StringUtils.isEmpty(res)) {
			logger.error("res=null");
			return null;
		}
		
		WeixinAccessTokenDomain weixinAccessTokenDomain = FastJsonConvert.convertJSONToObject(res, WeixinAccessTokenDomain.class);
		logger.debug("weixinAccessTokenDomain={}", weixinAccessTokenDomain);
		
		return weixinAccessTokenDomain;
	}
	
	
	/**
	 * 获取token
	 * @return
	 */
	public static String token() {
		
		String token = tokenData.getValue();
		if(StringUtils.isNotEmpty(token)) {
			return token;
		}
		
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
		url = String.format(url, Constants.WX_APPID, Constants.WX_APPSECRET);
		String res = HttpClientUtil.httpGetRequest(url);
		
		logger.info("res={}", res);
		
		JsonObject jsonObj = new JsonParser().parse(res).getAsJsonObject();
		token = jsonObj.get("access_token").getAsString();
		long expires_in = jsonObj.get("expires_in").getAsLong();
		tokenData = new DataExpiresIn<String>(token, expires_in);
		return token;
	}
	
	/**
	 * 向用户推关消息
	 * @param openid
	 * @param content
	 * @return
	 */
	public static boolean sendMsg(String openid, String content) {
		String access_token = token();
		String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token;
		
		JSONObject json = new JSONObject();
		try {
			json.put("touser", openid);
			json.put("msgtype", "text");
			
			content = new String(content.getBytes(), "utf-8");// ISO-8859-1 utf-8
			
			JSONObject textObj = new JSONObject();
			textObj.put("content", content);
			json.put("text", textObj);
			
			String reqStr = json.toString();
			logger.info("reqStr={}", reqStr);
			
			String res = HttpClientUtil.httpPostRequestJson(url, reqStr);
			logger.info("res={}", res);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static WeixinUser userInfo(String openid) {
		String access_token = token();
		
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
		String res = HttpClientUtil.httpGetRequest(url);
		WeixinUser wxUser = FastJsonConvert.convertJSONToObject(res, WeixinUser.class);
		return wxUser;
	}
	
	
	public static WeixinPayRes unifiedorder(WeixinPayDomain wxPayDomain) {
		String postXml = JaxbObjectAndXmlUtil.object2Xml(wxPayDomain, true);
        logger.info("pay postXml={}", postXml);
        
		String resXml = HttpClientUtil.httpPostRequestXml(Constants.WXPAY_UNIFIEDORDER, postXml);
		
		logger.info("pay resXml={}", resXml);
		
		WeixinPayRes weixinPayRes = JaxbObjectAndXmlUtil.xml2Object(resXml, WeixinPayRes.class);
		
		logger.debug("pay weixinPayRes={}", weixinPayRes);
		
		return weixinPayRes;
	}
	
	// js api获取签名使用
    public static String getTicket() {

    	String ticket = ticketData.getValue();
		if(StringUtils.isNotEmpty(ticket)) {
			return ticket;
		}
		
		String token = token();
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi";
        String res = HttpClientUtil.httpGetRequest(url);
		
        JsonObject jsonObj = new JsonParser().parse(res).getAsJsonObject();
        ticket = jsonObj.get("ticket").getAsString();
		long expires_in = jsonObj.get("expires_in").getAsLong();
		
		logger.info("res={}", res);
		
        ticketData = new DataExpiresIn<String>(ticket, expires_in);
        return ticket;
    }
    
    public static String getNews() {
    	
    	String token = token();
    	String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + token;
    	
    	String json = "{\"type\":\"news\", \"offset\":0, \"count\":50}";
    	String res = HttpClientUtil.httpPostRequestJson(url, json);
    	
        JsonObject jsonObj = new JsonParser().parse(res).getAsJsonObject();
        JsonArray items = jsonObj.getAsJsonArray("item");
        for(int i=0; i<items.size(); i++) {
        	JsonObject item = items.get(i).getAsJsonObject();
        	JsonObject content = item.get("content").getAsJsonObject();
        	
        	if(content.has("news_item")) {
        		JsonArray news_item = content.getAsJsonArray("news_item");
        		for(int j=0; j<news_item.size(); j++) {
        			JsonObject news = news_item.get(j).getAsJsonObject();
        			String title = news.get("title").getAsString();
        			String _url =  news.get("url").getAsString();
        			
        			System.out.println("title=" + title + ",url=" + _url);
        		}
        	}
        }
        
        return null;
    }
    
    public static String getQRUrl(String seneStr) {
    	
    	String token = token();
    	String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token;
    	
    	String json = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+seneStr+"\"}}}";
    	
    	String res = HttpClientUtil.httpPostRequestJson(url, json);
    	
    	JsonObject jsonObj = new JsonParser().parse(res).getAsJsonObject();
    	String ticket = jsonObj.get("ticket").getAsString();
    	String qrContent = jsonObj.get("url").getAsString(); // 二维码内容 - 可自已生成自定义图片
    	
    	try {
	    	ticket = URLEncoder.encode(ticket, "utf-8");
	    	String qrUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
	    	logger.info("qrUrl={}", qrUrl);
	    	return qrUrl;
    	} catch(Exception e) {
    		logger.error("{}", e.getMessage(), e);
    	}
    	return null;
    }
    
	public static void main(String[] args) throws Exception {
		
//		String openid = "owZ3jv5Wrc6S2NShemtkO5jvvVQU";
//		openid = "ohhK1s7W_wd7OHRVOejN2zjpHrkk";
//		openid = "ohhK1s1I_CzXizwbk1CQlKTMYScM";
//		openid = "ohhK1s96o-ZlFcKAoqM3tx6Lzn2I";
//		
//		sendMsg(openid, "测试消息-收到了微信回我一下 lei");
		
		String qrUrl = getQRUrl("574bc534cd054434aa309e7607b0d50f");
		System.out.println(qrUrl);
		
		// sendMsg(openid, "look 您有新订单请查收<a href=''>查看</a>");
//		System.out.println(userInfo(openid));
//		String ss = "[subscribe=1, openid=owZ3jv5Wrc6S2NShemtkO5jvvVQU, nickname=é·æ­¦é®, sex=1, language=zh_CN, city=ä¸å, province=åäº¬, country=ä¸­å½, headimgurl=http://wx.qlogo.cn/mmopen/yTwEBiarWOGdt84Mv2LCxplaSH73K6qtC1Iu06HoQWYHNibd1AodY051teyqLvu13cMSYxEuSZgk5qAicaaL5ErFricPNnGVMe7b/0, subscribe_time=1480635061, unionid=null, remark=, groupid=0, tagid_list=[], errcode=0, errmsg=null]";
//		System.out.println(new String(ss.getBytes("iso8859-1"), "utf-8"));
		
//		getUserTokenAndOpenidByCode("001mZCtT1NqUK918XXrT1IwxtT1mZCtu");
		
		
//		String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg><appid><![CDATA[wx2421b1c4370ec43b]]></appid><mch_id><![CDATA[10000100]]></mch_id><nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str><openid><![CDATA[oUpF8uMuAJO_M2pxb1Q9zNjWeS6o]]></openid><sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign><result_code><![CDATA[SUCCESS]]></result_code><prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id><trade_type><![CDATA[JSAPI]]></trade_type></xml>";
//		System.out.println(JaxbObjectAndXmlUtil.xml2Object(resXml, WeixinPayRes.class));
//		
//		WeixinPayDomain wxPayDomain = new WeixinPayDomain();
//		wxPayDomain.detail = "fdsafs";
//		wxPayDomain.appid = "fdafds";
//		System.out.println(JaxbObjectAndXmlUtil.object2Xml(wxPayDomain, false));
		
	}

}
